package com.zsw.recongize.parse;

import java.awt.Rectangle;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zsw.recongize.bean.Invoice;
import com.zsw.recongize.result.JxlWrite;

public class PdfBoxParse {
	
	private final static String REGION_NAME = "regionName";
	
	private final static Logger LOG = LoggerFactory.getLogger(PdfBoxParse.class);
	/**
	 * 只看发票的话看日期，公司名称，税号，发票章，开发票的公司名，发票明细，金额
	 * @param sourcePath
	 * @param targetPath
	 * @return
	 */
	public static String pase(String sourcePath, String targetPath, String buyerName, String buyerSocialCode){
		File file = new File(sourcePath);
		List<Invoice> list = new ArrayList<Invoice>();
		if(file.isFile()){
			list.add(pase(file, buyerName, buyerSocialCode));
		}else{
			File[] files = file.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					return name.endsWith("pdf");
				}
			});
			for(File f: files){
				list.add(pase(f, buyerName, buyerSocialCode));
			}
		}
		File targetFile = new File(targetPath + "/" + System.currentTimeMillis() + ".xls");
		JxlWrite.export(list, targetFile);
		return targetFile.getAbsolutePath();
	}
	
	public static Invoice pase(File file, String buyerName, String buyerSocialCode){
		Invoice invoice = new Invoice();
		invoice.setFileName(file.getName());
		try {
			return pase(invoice, new FileInputStream(file), buyerName, buyerSocialCode);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return invoice;
	}
	public static Invoice pase(Invoice invoice, InputStream in, String buyerName, String buyerSocialCode){
		PDDocument document = null;
		try{
			document = PDDocument.load(in);
			PDFTextStripperByArea stripper = new PDFTextStripperByArea();
			stripper.setSortByPosition(true);
			PDPage pg0 = document.getDocumentCatalog().getPages().get(0);
            
            Rectangle rect = new Rectangle(40, 92, 300, 100);
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            String text = stripper.getTextForRegion(REGION_NAME);
            String[] texts = text.split("[\\n]");
            int i = 0;
            if(texts[0].indexOf("编") >= 0 && texts[0].indexOf("码") >= 0){
            	i++;
            }
            String buyerName_ = texts[i].split("[：:]")[1].trim();
            if(buyerName_.length() > 0 && buyerName_.equals(buyerName)){
            	invoice.setBuyerNameCorrect(true);
            }
            invoice.setBuyerName(buyerName_);
            String buyerSocialCode_ = texts[i + 1].split("[：:]")[1].trim();
            if(buyerSocialCode_.length() > 0 && buyerSocialCode_.equals(buyerSocialCode)){
            	invoice.setBuyerSocialCodeCorrect(true);
            }
            invoice.setBuyerSocialCode(buyerSocialCode_);
            invoice.setBuyerAddress(texts[i + 2].split("[：:]")[1].trim());
            invoice.setBuyerBankAccount(texts[i + 3].split("[：:]")[1].trim());
            
            rect = new Rectangle(410, 0, 400, 150);
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            texts = text.split("[\\n]");
            i = 0;
            invoice.setCode(texts[i + 0].split("[：:]")[1].trim());
            invoice.setNumber(texts[i + 1].split("[：:]")[1].trim());
            invoice.setDate(texts[i + 2].split("[：:]")[1].trim());
            invoice.setCheckCode(texts[i + 3].split("[：:]")[1].trim());
            
            rect = new Rectangle(370, 90, 400, 60);
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            invoice.setPassword(text.trim());
            
            rect = new Rectangle(40, 300, 275, 60);
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            texts = text.split("[\\n]");
            invoice.setSellerName(texts[0].split("[：:]")[1].trim());
            invoice.setSellerSocialCode(texts[1].split("[：:]")[1].trim());
            invoice.setSellerAddress(texts[2].split("[：:]")[1].trim());
            invoice.setSellerBankAccount(texts[3].split("[：:]")[1].trim());
            
            rect = new Rectangle(20, 166, 145, 104);
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            invoice.setDetailGoods(text.trim());
            
            rect = new Rectangle(165, 166, 50, 104);//规格型号
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            invoice.setDetailModel(text.trim());
//            System.out.println(text.trim());
            
            rect = new Rectangle(215, 166, 30, 104);//单位
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            invoice.setDetailUnit(text.trim());
//            System.out.println(text.trim());
            
            rect = new Rectangle(240, 166, 80, 104);//数量
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            invoice.setDetailCount(text.trim());
//            System.out.println(text.trim());
            
            rect = new Rectangle(320, 166, 80, 104);//单价
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            invoice.setDetailUnitPrice(text.trim());
//            System.out.println(text.trim());
            
            rect = new Rectangle(400, 166, 80, 104);//金额
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            invoice.setDetailTotalPrice(text.trim());
//            System.out.println(text.trim());
            
            rect = new Rectangle(480, 166, 30, 104);//税率
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            invoice.setDetailTaxRate(text.trim());
//            System.out.println(text.trim());
            
            rect = new Rectangle(510, 166, 100, 104);//税额
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            invoice.setDetailTax(text.trim());
//            System.out.println(text.trim());
            
            rect = new Rectangle(440, 280, 300, 15);
            stripper.addRegion(REGION_NAME, rect);
            stripper.extractRegions(pg0);
            text = stripper.getTextForRegion(REGION_NAME);
            text = text.replaceAll("[(（]小写[)）]", "");
            invoice.setTotal(text.trim());
        }catch(Exception e){
        	LOG.error(e.getMessage(), e);
            invoice.setExceptionMsg(e.getMessage());
        }finally{
        	if(document != null){
        		try {
        			document.close();
        		} catch (IOException e) {}
        	}
        }
		return invoice;
	}
	public static void main(String[] args){
//        File pdfFile = new File("D://invoice/files/电信电子发票56526383-201705.pdf");
//        File pdfFile = new File("D://invoice/files/56526385.pdf");
//        File pdfFile = new File("D://invoice/files/D59018762344沐浴露-6月.pdf");
        File pdfFile = new File("D://invoice/files/2月21日保温瓶2个发票.pdf");
//        File pdfFile = new File("D://invoice/files/5月18日凭证纸发票.pdf");
        PdfBoxParse.pase(pdfFile,"", "");
    }
}
